﻿Shader "My/Terrain"
{
    Properties
    {
        _MainTex ("MainTex", 2D) = "red" {}
        _Control ("Control", 2D) = "red" {}
        _Splat0 ("Splat0", 2D) = "red" {}
        _Splat1 ("Splat1", 2D) = "red" {}
        _Splat2 ("Splat2", 2D) = "red" {}
        _Splat3 ("Splat3", 2D) = "red" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        Pass
        {
            CGPROGRAM 
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 color : COLOR;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            sampler2D _Control;
            sampler2D _Splat0;
            sampler2D _Splat1;
            sampler2D _Splat2;
            sampler2D _Splat3;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                o.color = (1,1,1,1);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 control = tex2D(_Control, i.uv);

                fixed4 color = (0,0,0,0);

                color = tex2D(_Splat0, i.uv * 10) * control.r;
                color = tex2D(_Splat1, i.uv * 10) * control.g + color;
                color = tex2D(_Splat2, i.uv * 20) * control.b + color;
                if(color.a < 0.5)color = tex2D(_Splat3, i.uv * 8) + color;
                clip(color.a - 0.1);
                
                // 获取光照信息
                fixed3 lightDir = normalize(_WorldSpaceLightPos0.xyz);
                fixed3 normal = normalize(i.color.rgb); // 使用颜色作为法线
                float ndotl = max(0, dot(normal, lightDir)) + 1;

                return  color * ndotl;
            }
            ENDCG
        }
    }
}
